<?php
/**
 * Created by PhpStorm.
 * User: zhengze
 * Date: 2019/7/1
 * Time: 18:29
 */

namespace app\common\validate;

use app\common\exception\ArticleException;
use app\common\exception\ExceptionEmun;
use app\common\model\Article;
use app\common\model\Category;
use app\common\token\token;
use app\common\traits\InstanceTrait;
use app\common\validate\BaseValidate;

/**
 * Class ArticleValidate
 */
class ArticleValidate extends BaseValidate
{
    use InstanceTrait;

    protected $rule = [
        'id|ID' => ['require',],
        'ids|主键数组' => ['require',],
        'status|状态' => ['require',],
        'title|标题' => ['require',],
        'content|内容' => ['require',],
        'category_id|文章分类' => ['require',],
    ];

    protected $sceneRule = [
        'index' => [
            'only' => [''],
        ],
        'read' => [
            'only' => ['id'],
        ],
        'delete' => [
            'only' => ['id'],
        ],
        'deletes' => [
            'only' => ['ids'],
        ],
        'enables' => [
            'only' => ['ids', 'status'],
        ],
        'save' => [
            'only' => ['title', 'content', 'category_id'],
            'append' => [
                'title' => 'checkTitleUnique',
            ],
        ],
        'update' => [
            'only' => ['title', 'content', 'category_id'],
            'append' => [
                'title' => 'checkTitleUnique',
            ],
        ],
    ];

    /**
     * 检测名字重复
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    protected function checkTitleUnique($value, $rule, $data = [])
    {
        $admin_info = Token::instance()->getUserInfo();
        $article = Article::where('title', '=', $value)
                          ->where('creater_id', '=', $admin_info['admin_id'])
                          ->find();
        $pk = 'id';
        if (!empty($article)) {
            if (!empty($data[$pk])) {
                //修改
                if ($data[$pk] != $article['article_id']) {
                    return ExceptionEmun::throwException(ArticleException::NAME_REPEAT);
                }
            } else {
//                创建
                return ExceptionEmun::throwException(ArticleException::NAME_REPEAT);
            }
        }
        return true;
    }

    /**
     * 检测文章分类是否存在
     * @param $value
     * @return bool
     * @throws \Exception
     */
    protected function checkCategoryExist($value, $rule, $data = [])
    {
        $category = Category::find($value);
        if (empty($category)) {
            return ExceptionEmun::throwException(ArticleException::Category_EMPTY);
        }
        return true;
    }
}
